package com.ruoyi.common.utils.mybatis;

import com.ruoyi.common.core.domain.entity.SysUser;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 员工状态类型处理器 - 将数据库中的employee.status映射到SysUser.status
 */
@MappedTypes(String.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class EmployeeStatusTypeHandler extends BaseTypeHandler<String> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        // 用于写入数据库，根据SysUser.status设置employee.status
        switch (parameter) {
            case "0": // 正常状态映射到employee的probation或formal
                ps.setString(i, "formal"); // 默认映射为正式员工
                break;
            case "1": // 停用状态映射到employee的leave
                ps.setString(i, "leave");
                break;
            default:
                ps.setString(i, "retired");
        }
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        // 从数据库读取时，将employee.status映射到SysUser.status
        String status = rs.getString(columnName);
        if (status == null) {
            return "1"; // 默认为停用
        }
        switch (status) {
            case "probation":
            case "formal":
                return "0"; // 正常
            case "leave":
            case "retired":
                return "1"; // 停用
            default:
                return "1";
        }
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String status = rs.getString(columnIndex);
        if (status == null) {
            return "1";
        }
        switch (status) {
            case "probation":
            case "formal":
                return "0";
            case "leave":
            case "retired":
                return "1";
            default:
                return "1";
        }
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String status = cs.getString(columnIndex);
        if (status == null) {
            return "1";
        }
        switch (status) {
            case "probation":
            case "formal":
                return "0";
            case "leave":
            case "retired":
                return "1";
            default:
                return "1";
        }
    }
}